package cn.minimelon.api.controller.common;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import cn.minimelon.api.constant.Constants;
import cn.minimelon.api.domain.common.AjaxResult;
import cn.minimelon.api.service.common.ISysConfigService;
import cn.minimelon.api.utils.captcha.ImageVerificationCode;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Get;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.data.cache.CacheService;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 验证码操作处理
 *
 * @author ruoyi
 */
@Controller
public class CaptchaController {
    @Inject
    CacheService cacheService;

    @Inject
    ISysConfigService configService;

    /**
     * 生成验证码
     */
    @Get
    @Mapping("/captchaImage")
    public AjaxResult getCode() throws IOException {
        AjaxResult ajax = AjaxResult.success();
        boolean captchaOnOff = configService.selectCaptchaOnOff();
        ajax.put("captchaEnabled", captchaOnOff);
        if (!captchaOnOff) {
            return ajax;
        }

        // 保存验证码信息
        String uuid = IdUtil.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        ImageVerificationCode verificationCode = new ImageVerificationCode();

        BufferedImage image = verificationCode.getImage(); // 生成验证码
        String code = verificationCode.getText();

        cacheService.store(verifyKey, code, Constants.CAPTCHA_EXPIRATION);
        // 转换流信息写出
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }
}
